package cn.ibizlab.util.domain;

import cn.ibizlab.util.helper.RequestWrapperDeserializer;
import cn.ibizlab.util.domain.DTOBase;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;

@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
@JsonIgnoreProperties(value = "handler")
@JsonDeserialize(using = RequestWrapperDeserializer.class)
public class RequestWrapper<T> {

  @JsonIgnore
  @JSONField(serialize = false)
  private List<T> list;

  @JsonIgnore
  @JSONField(serialize = false)
  private T dto;

  @JsonIgnore
  @JSONField(serialize = false)
  private boolean array =false;

  public RequestWrapper<T> setList(List<T> list) {
    this.array = true;
    if (list!=null && list.size()==1)
      this.dto = list.get(0);
    this.list = list;
    return this;
  }

  public RequestWrapper setDto(T dto) {
    this.array = false;
    this.list = Arrays.asList(dto);
    this.dto = dto;
    return this;
  }

  @JsonIgnore
  @JSONField(serialize = false)
  public T get() {
    if(this.array && !ObjectUtils.isEmpty(this.list))
      return list.get(0);
    return this.dto;
  }

  public RequestWrapper<T> set(Object content) {
    if(content.getClass().isArray())
      return setList((List<T>) content);
    else
      return setDto((T) content);
  }
}